<template>
	<div style="background-color: #FFFFFF; width: 100%; height: 100%; padding: 15px;">
		<a-spin :spinning="loading">
			<div style="display:flex;">
				<div style="flex:1;margin-left: 26px; font-size: 13px; font-weight: bold;">
					<span>工序电耗</span>
				</div>
				<div class="tit">
					<a-button type="primary" @click="goBuckMachineEleConsum"  v-if="machineEleLevel == 2" :span="3"> <a-icon type="left" />返回上一页 </a-button>
				</div>
				
			</div>
			<div style="margin-left: 20px;margin-top: 20px; padding:5px">
				<a-row :gutter="16">
					<a-col :span="6">
						<j-dict-select-tag style="width: 100%" placeholder="请选择公司" v-model="queryParam.company"
							dictCode="crm_company,name,id" disabled />
					</a-col>
					<a-col :span="4">
						<div style="display: flex;">
							<a-dropdown>
								<a-menu slot="overlay" @click="handleElecConsumClick">
									<a-menu-item key="2"> 车间电耗 </a-menu-item>
									<a-menu-item key="3"> 当班电耗 </a-menu-item>
								</a-menu>
								<a-button style="margin-left: 1px"> {{ selectedElecConsum }} <a-icon type="down" />
								</a-button>
							</a-dropdown>
						</div>
					</a-col>
					<a-col :span="6" v-if="viewWorkshop">
						<div id="workShop">
							<div style="display: flex;">
								<div>
									<a-dropdown>
										<a-menu slot="overlay" @click="handleWorkshopClick">
											<a-menu-item v-for="workShop in workShops" :key="workShop.value"
												:value="workShop.label">
												{{ workShop.label }}
											</a-menu-item>
										</a-menu>
										<a-button style="margin-left: 1px"> {{ selectedWorkshop }} <a-icon
												type="down" /> </a-button>
									</a-dropdown>
								</div>
							</div>
						</div>
					</a-col>
					<a-col :span="6">
						<div id="JiaYiBan" style="margin-left: -16px;">
							<div style="display: flex;" v-if="viewShift">
								<div>
									<a-dropdown>
										<a-menu slot="overlay" @click="handleShiftClick">
											<!-- 动态生成菜单项 -->
											<a-menu-item v-for="shift in shifts" :key="shift.value"
												:value="shift.label">
												{{ shift.label }}
											</a-menu-item>
										</a-menu>
										<a-button style="margin-left: 1px">
											{{ selectedShift }} <a-icon type="down" />
										</a-button>
									</a-dropdown>
								</div>
							</div>
						</div>
					</a-col>
				</a-row>
				<div style="display:flex; flex-direction: row">
					<keep-alive>
						<div v-if="viewPageChange">
							<RangePicker v-model="date" :rangeValue="rangeValue" @handleRadioChange="handleRadioChange">
							</RangePicker>
						</div>
					</keep-alive>
					<div v-if="!viewPageChange"
						style="width: 350px;margin-top: 10px; display: flex;flex-direction: row">
						<a-date-picker v-model="startValue" show-time format="YYYY-MM-DD HH:mm:ss" placeholder="请输入开始时间"
							@openChange="handleStartOpenChange" @change="handleStartChange()" />
						<a-date-picker v-model="endValue" :show-time="{
                 hideDisabledOptions: true
              }" format="YYYY-MM-DD HH:mm:ss" placeholder="请输入结束时间" :open="endOpen" :disabled-time="disabledRangeTime"
							@openChange="handleEndOpenChange" @change="handleEndChange()" style="margin-left: 10px;" />
					</div>
					<a-button @click="onSearch" type="primary" style="margin-top: 10px;margin-left: 96px">
						查询
					</a-button>
				</div>
				<div>
					<a-row>
						<a-col :span="4" v-for="(machineEleConsum,index) in machineEleArr " :key="index"
							v-if="machineEleLevel== 1">

							<div id="squareMachine" @click="nextMachineEleConsum(machineEleConsum)">
								<div>
									{{machineEleLevel== 1 ? machineEleConsum.productCategory_dictText : machineEleConsum.productTypeTxt}}
								</div>
								<div style="margin-top:10px;font-size: large">
									<b>{{ machineEleConsum.consumption}}</b><span>{{"(kwh)"}}</span>
								</div>
							</div>
						</a-col>

						<a-col :span="4" v-for="(machineEleConsum,index) in machineEleArr " :key="index"
							v-if="machineEleLevel== 2">

							<div id="squareMachine" @click="nextMachineEleConsum(machineEleConsum)">
								<div>
									{{machineEleLevel== 1 ? machineEleConsum.productCategory_dictText : machineEleConsum.productTypeTxt}}
								</div>
								<div style="margin-top:10px;font-size: large">
									<b>{{ machineEleConsum.consumption}}</b><span>{{"(kwh)"}}</span>
								</div>
							</div>
						</a-col>

					</a-row>
				</div>
				<div>
					<div id="tree"></div>
				</div>
				<div style="display: flex;justify-content: space-between;">
					<div id="pieOne" v-if="machineEleLevel== 1"></div>
					<div id="pieTwo"></div>
				</div>
			</div>

		</a-spin>
	</div>
</template>
<script>
	import * as echarts from 'echarts';
	import {
		formatDate
	} from '@/utils/util';
	import RangePicker from '@/components/RangePicker/RangePicker.vue'
	import {
		getTnergyManageConsumptionSum,
		ajaxGetDictItems
	} from '@/api/api'
	import dayjs from 'dayjs'
	import {
		getAction
	} from '@api/manage'
	import moment from 'moment/moment'
	export default {
		name: "energyActual",
		components: {
			RangePicker
		},
		data() {
			return {
				loading: false,
				gather: [],
				workshop: [],
				onTurn: [],
				selectedElecConsum: '车间电耗',
				selectedShift: '',
				selectedWorkshop: '', // 默认显示 '全部'
				keyShift: "",
				viewWorkshop: true,
				viewShift: false,
				viewPageChange: true,
				shifts: [],
				workShops: [],
				machineEleConsums: [],
				date: null,
				optionTreeData: {},
				optionPieOneData: {},
				optionPieTwoData: {},
				rangeValue: "a",
				riqi: dayjs().format('YYYY-MM-DD 00:00:00'),
				endOpen: false,
				startOpen: false,
				startValue: null,
				endValue: null,
				queryParam: {
					company: '1771136798305476610',
					endTime: "",
					startTime: "",
					workshop: ""
				},
				machineEleArr: [],
				machineEleLevel: 1,
				selectQuery: {
					company: '1771136798305476610',
					deviceNo: undefined,
					endTime: undefined,
					productCategory: undefined,
					startTime: undefined,
					workshop: undefined,
					pageSize: 30000,
					pageNo: 1
				},
			};
		},

		mounted() {
			this.initData()
			this.getTreeData()
			this.getPieOneData()
			this.getPieTwoData()
		},
		methods: {
			nextMachineEleConsum(msg) {
				this.machineEleLevel = 2
				this.machineEleArr = []
				this.machineEleConsums = []
				this.selectQuery.productCategory = msg.productCategory
				this.onSearch()
			},
			goBuckMachineEleConsum() {
				this.machineEleArr = []
				this.machineEleConsums = []
				this.machineEleLevel = 1
				this.onSearch()
			},
			initData() {
				ajaxGetDictItems("shift", {
					id: "1772622847011680257"
				}).then((res) => {
					this.keyShift = res.result[0].value;
					this.selectedShift = res.result[0].label;
					this.shifts = res.result;
				})
				ajaxGetDictItems("workshop", {
					id: "1810244762893209601"
				}).then((res) => {
					this.workShops = res.result;
					this.queryParam.workshop = res.result[0].value;
					this.selectedWorkshop = res.result[0].label;
					this.queryParam.startTime = dayjs().format('YYYY-MM-DD 00:00:00')
					this.queryParam.endTime = dayjs().add(1, 'day').format('YYYY-MM-DD  00:00:00')
					this.onSearch()
				})
			},
			handleElecConsumClick({
				key
			}) {
				this.viewShift = false
				this.viewWorkshop = false
				if (key == 2) {
					this.viewWorkshop = true
					this.viewPageChange = true
					ajaxGetDictItems("workshop", {
						id: "1810244762893209601"
					}).then((res) => {
						this.workShops = res.result;
					})
					this.queryParam.startTime = this.date[0];
					this.queryParam.endTime = this.date[1];
					this.onSearch()
				}
				if (key == 3) {
					this.viewShift = true
					this.viewPageChange = false
					this.queryParam.workshop = ""
					if (this.keyShift == "1") {
						this.queryParam.startTime = dayjs(this.riqi).format('YYYY-MM-DD 00:00:00')
						this.queryParam.endTime = dayjs(this.riqi).format('YYYY-MM-DD 12:00:00')
					} else {
						this.queryParam.startTime = dayjs(this.riqi).format('YYYY-MM-DD 12:00:00')
						this.queryParam.endTime = dayjs(this.riqi).add(1, "day").format('YYYY-MM-DD 00:00:00')
					}

					ajaxGetDictItems("shift", {
						id: "1772622847011680257"
					}).then((res) => {
						this.shifts = res.result;
					})
					this.onSearch()
				}
				const options = {
					2: '车间电耗',
					3: '当班电耗',
				};
				this.selectedElecConsum = options[key] || '车间电耗';
			},

			handleWorkshopClick({
				key
			}) {
				// 根据点击的 key 来更新按钮文本
				const workShopItem = this.workShops.find(workShop => workShop.value === key);
				this.selectedWorkshop = workShopItem.text;
				this.queryParam.workshop = key;

			},
			handleShiftClick({
				key
			}) {
				// 根据点击的 key 来更新按钮文本
				const shiftItem = this.shifts.find(shift => shift.value === key);
				this.selectedShift = shiftItem.text;
				this.keyShift = shiftItem.value;
				if (this.keyShift == "1") {
					this.queryParam.startTime = dayjs(this.riqi).format('YYYY-MM-DD 00:00:00')
					console.log(this.queryParam.startTime, "  this.queryParam.startTime")
					this.queryParam.endTime = dayjs(this.riqi).format('YYYY-MM-DD 12:00:00')
				} else {
					this.queryParam.startTime = dayjs(this.riqi).format('YYYY-MM-DD 12:00:00')
					this.queryParam.endTime = dayjs(this.riqi).add(1, "day").format('YYYY-MM-DD 00:00:00')
				}
				this.onSearch()
			},
			handleRadioChange(e) {
				this.$nextTick(() => {
					this.queryParam.startTime = this.date[0];
					this.queryParam.endTime = this.date[1];
					this.rangeValue = e
				})
			},
			handleStartOpenChange(open) {
				this.startOpen = open;
				if (!open) {
					this.endOpen = true;
				}
				// 当结束时间选择器打开时，将结束时间设置为开始时间
				if (open && this.startValue) {
					this.endValue = dayjs(this.startValue).format('YYYY-MM-DD HH:mm:ss');
				}
			},
			range(start, end) {
				const result = [];
				for (let i = start; i < end; i++) {
					result.push(i);
				}
				return result;
			},
			disabledRangeTime(_, type) {
				console.log(this.startValue)
				// 从 startValue 提取小时、分钟和秒
				const startHour = this.startValue ? dayjs(this.startValue).hour() : null;
				const startMinute = this.startValue ? dayjs(this.startValue).minute() : null;
				const startSecond = this.startValue ? dayjs(this.startValue).second() : null;

				return {
					// 禁用的小时
					disabledHours: () => {
						const hours = this.range(0, 24);
						if (startHour !== null) {
							// 如果 startHour 有值，则禁用 startHour 之后的所有小时
							return hours.filter(hour => hour < startHour);
						}
						return [];
					},
					// 禁用的分钟
					disabledMinutes: (selectedHour) => {
						const minutes = this.range(0, 60);
						if (startMinute !== null) {
							if (selectedHour === startHour) {
								// 如果 startMinute 有值，并且 startHour 与当前小时相同，则禁用 startMinute 之后的所有分钟
								return minutes.filter(minute => minute < startMinute);
							}
						}
						return [];
					},
					// 禁用的秒
					disabledSeconds: (selectedMinutes) => {
						// 如果 startSecond 有值，并且 startHour 和 startMinute 都相同，则禁用 startSecond 之后的所有秒
						if (startSecond !== null) {
							const seconds = this.range(0, 60);
							if (selectedMinutes === startMinute) {
								// 如果 startMinute 有值，并且 startHour 与当前小时相同，则禁用 startMinute 之后的所有分钟
								return seconds.filter(second => second < startSecond);
							}
						}
						return [];
					},
				}
			},
			handleEndOpenChange(open) {
				this.endOpen = open;
			},
			handleStartChange() {
				if (this.endValue === null) {
					this.endValue = dayjs().format('YYYY-MM-DD HH:mm:ss');
				}
				// 获取开始时间的年月日
				const datePart = dayjs(this.startValue).format('YYYY-MM-DD');
				// 获取结束时间的时分秒部分
				const timePart = dayjs(this.endValue).format('HH:mm:ss');

				// 将结束时间的年月日设为开始时间的年月日
				this.endValue = dayjs(`${datePart} ${timePart}`).format('YYYY-MM-DD HH:mm:ss'); // 创建新的 dayjs 对象
				this.queryParam.startTime = dayjs(this.startValue).format('YYYY-MM-DD HH:mm:ss')

			},
			handleEndChange() {
				if (this.startValue === null) {
					this.startValue = dayjs().format('YYYY-MM-DD HH:mm:ss');
				}
				// 获取开始时间的年月日
				const datePart = dayjs(this.endValue).format('YYYY-MM-DD');
				// 获取结束时间的时分秒部分
				const timePart = dayjs(this.startValue).format('HH:mm:ss');
				this.startValue = dayjs(`${datePart} ${timePart}`).format('YYYY-MM-DD HH:mm:ss');
				this.disabledRangeTime(_, 0);
				this.queryParam.endTime = dayjs(this.endValue).format('YYYY-MM-DD HH:mm:ss')
			},
			getTreeData() {
				var myChart = echarts.init(document.getElementById('tree'));
				this.optionTreeData = {
					tooltip: {
						trigger: 'axis',
						axisPointer: {
							type: 'shadow'
						},
						formatter: function(params) {
							var relVal = params[0].name
							for (var i = 0, l = params.length; i < l; i++) {
								relVal += '<br/>' + params[i].marker + params[i].value + 'kw·h'
							}
							return relVal
						}
					},

					grid: {
						left: '3%',
						right: '4%',
						bottom: '3%',
						containLabel: true
					},
					xAxis: [{
						type: 'category',
						// data: ['清花', '梳棉', '并条', '粗纱', '细纱', '络筒', '打包'],
						data: [],
						axisTick: {
							alignWithLabel: true
						}
					}],
					yAxis: [{
						type: 'value',
						name: '单位:kw·h'
					}],
					series: [{
						// name: 'Direct',
						type: 'bar',
						barWidth: '10%',
						data: []
					}]
				};
				this.optionTreeData.xAxis[0].data = this.machineEleConsums.map(item => this.machineEleLevel == 1 ? item
					.productCategory_dictText : item.productTypeTxt);
				this.optionTreeData.series[0].data = this.machineEleConsums.map(item => item.consumption);

				// 打印转换后的 label 数组
				myChart.setOption(this.optionTreeData);
			},
			getPieOneData() {
				var myChart = echarts.init(document.getElementById('pieOne'));
				this.optionPieOneData = {
					title: {
						text: this.machineEleLevel == 1 ? '前纺汇总电耗' : '各品种电耗',
						left: 'center'
					},
					tooltip: {
						trigger: 'item',
						formatter: function(params) {

							return `${params.marker}${params.name}    ${params.value} kw·h  ${params.percent} %`;
						}
					},
					legend: {
						orient: 'vertical',
						left: 'left'
					},
					series: [{
						type: 'pie',
						radius: '50%',
						data: [{
								value: 2.22,
								name: '清花'
							},
							{
								value: 68.6,
								name: '梳棉'
							},
							{
								value: 0.71,
								name: '并条'
							},
							{
								value: 28.47,
								name: '粗纱'
							}
						],
						emphasis: {
							itemStyle: {
								shadowBlur: 10,
								shadowOffsetX: 0,
								shadowColor: 'rgba(0, 0, 0, 0.5)'
							}
						}
					}]
				};
				// 使用 map() 来转换数组
				if (this.machineEleLevel == 1) {
					var transformedData = this.machineEleConsums.filter(item => item.productCategory != 1 && item
						.productCategory != 10).map(item => ({
						name: this.machineEleLevel == 1 ? item.productCategory_dictText : item
							.productTypeTxt, // 将 productCategory_dictText 变为 name
						value: item.consumption // 将 consumption 变为 value
					}));
				} else {
					var transformedData = this.machineEleConsums.map(item => ({
						name: this.machineEleLevel == 1 ? item.productCategory_dictText : item
							.productTypeTxt, // 将 productCategory_dictText 变为 name
						value: item.consumption // 将 consumption 变为 value
					}));
				}
				this.optionPieOneData.series[0].data = transformedData
				myChart.setOption(this.optionPieOneData);
			},
			getPieTwoData() {
				var myChart = echarts.init(document.getElementById('pieTwo'));
				this.optionPieTwoData = {
					title: {
						text: this.machineEleLevel == 1 ? '细纱/络筒汇总电耗' : '各品种电耗',
						left: 'center'
					},
					tooltip: {
						trigger: 'item',
						formatter: function(params) {
							return `${params.marker}${params.name}    ${params.value} kw·h  ${params.percent} %`;
						}
					},
					legend: {
						orient: 'vertical',
						left: 'left'
					},
					series: [{
						type: 'pie',
						radius: '50%',
						data: [{
								value: 12033.8,
								name: '莱赛尔40S紧赛纺 LJ308066'
							},
							{
								value: 1979.9,
								name: '莱赛尔50S紧赛纺 LJ312955'
							},
							{
								value: 3774.1,
								name: '莱赛尔30S紧赛纺 LJ306088-7'
							}
						],
						emphasis: {
							itemStyle: {
								shadowBlur: 10,
								shadowOffsetX: 0,
								shadowColor: 'rgba(0, 0, 0, 0.5)'
							}
						}
					}]
				};
				// 使用 map() 来转换数组
				if (this.machineEleLevel == 1) {
					var transformedData = this.machineEleConsums.filter(item => item.productCategory == 1 || item
						.productCategory == 10).map(item => ({
						name: this.machineEleLevel == 1 ? item.productCategory_dictText : item
							.productTypeTxt, // 将 productCategory_dictText 变为 name
						value: item.consumption // 将 consumption 变为 value
					}));
				} else {
					var transformedData = this.machineEleConsums.map(item => ({
						name: this.machineEleLevel == 1 ? item.productCategory_dictText : item
							.productTypeTxt, // 将 productCategory_dictText 变为 name
						value: item.consumption // 将 consumption 变为 value
					}));
				}
				this.optionPieTwoData.series[0].data = transformedData
				myChart.setOption(this.optionPieTwoData);
			},

			onSearch() {
				this.loading = true;
				console.log("this.machineEleLevel",this.machineEleLevel)
				if (this.machineEleLevel == 1) {
					getTnergyManageConsumptionSum(this.queryParam).then((res) => {
						this.machineEleConsums = res.result.records;
						var data = {
							productCategory_dictText: '总电耗',
							consumption: 0
						}
						this.machineEleArr = JSON.parse(JSON.stringify(res.result.records));
						for (var i = 0; i < this.machineEleArr.length; i++) {
							data.consumption += this.machineEleArr[i].consumption
						}
						this.machineEleArr.unshift(data)

						this.getTreeData()
						this.getPieOneData()
						this.getPieTwoData()
						this.loading = false
					})

				} else {
					this.selectQuery.startTime = this.queryParam.startTime
					this.selectQuery.endTime = this.queryParam.endTime
					this.selectQuery.workshop = this.queryParam.workshop
					getAction('/zjc_consumption/zjcConsumption/energyManageVarietyElectricityConsumption', this
						.selectQuery).then(
						res => {
							this.machineEleConsums = res.result.records;
							var data = {
								productCategory_dictText: '总电耗',
								productTypeTxt: '总电耗',
								consumption: 0
							}
							this.machineEleArr = JSON.parse(JSON.stringify(res.result.records));
							for (var i = 0; i < this.machineEleArr.length; i++) {
								if(i==0){
									data.productTypeTxt=this.machineEleArr[i].productCategory_dictText+'总电耗'
								}
								data.consumption += this.machineEleArr[i].consumption
							}
							this.machineEleArr.unshift(data)

							this.getTreeData()
							// this.getPieOneData()
							this.getPieTwoData()
							this.loading = false
						}
					)
				}
			},
		},
	};
</script>
<style lang="less" scoped>
	#tree {
		width: 100%;
		height: 200px;
		margin-left: -30px;
	}

	#pieOne {
		width: 450px;
		height: 450px;
		margin: 50px 50px 0 83px;
		display: inline-flex;
	}

	#pieTwo {
		width: 450px;
		height: 450px;
		margin: 50px 50px 0 50px;
		display: inline-flex;
	}

	#pieThree {
		width: 450px;
		height: 450px;
		margin: 50px 50px 0 50px;
		display: inline-flex;
	}

	#squareMachine {
		margin-right: 10px;
		margin-top: 10px;
		border-top: 1px solid black;
		border-right: 1px solid black;
		border-bottom: 1px solid black;
		border-left: 1px solid black;
		padding: 10px 15px;
		cursor: pointer;
	}

	::v-deep .ant-col-3 {
		width: 10.5%;
	}


	.time-only-picker .ant-picker-date-panel {
		display: none;
	}

	/* 确保时间选择面板显示 */
	.time-only-picker .ant-picker-time-panel {
		display: block !important;
	}
</style>